<template>
  <ContentWrap>
    <!-- 搜索工作栏（不新增 marketing_tools 搜索项） -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="号码" prop="phoneE164">
        <el-input
          v-model="queryParams.phoneE164"
          placeholder="请输入号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="分数" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入分数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item label="MD5" prop="phoneMd5">
        <el-input
          v-model="queryParams.phoneMd5"
          placeholder="请输入手机MD5"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <!-- 业务标签：多选 字典 PHONE_TAG -->
      <el-form-item label="业务标签" prop="phoneTags">
        <el-select
          v-model="queryParams.phoneTags"
          placeholder="请选择业务标签"
          multiple
          collapse-tags
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PHONE_TAG)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="AccountId" prop="secretId">
        <el-input
          v-model="queryParams.secretId"
          placeholder="请输入AccountId"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="应答时间" prop="responseTime">
        <el-date-picker
          v-model="queryParams.responseTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <!-- 应答状态：使用 RESPONSE_STATE 枚举（0未应答/1注册/2成交） -->
      <el-form-item label="应答状态" prop="responseState">
        <el-select
          v-model="queryParams.responseState"
          placeholder="请选择应答状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.RESPONSE_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="租户ID" prop="rechargeTenantId">
        <el-input
          v-model="queryParams.rechargeTenantId"
          placeholder="请输入租户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="名单等级" prop="listLevel">
        <el-select
          v-model="queryParams.listLevel"
          placeholder="请选择名单等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.LIST_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['vos:marketing-list-log:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="号码" align="center" prop="phoneE164" />
      <el-table-column label="分数" align="center" prop="score" />

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <el-table-column label="MD5" align="center" prop="phoneMd5" />

      <!-- 业务标签列：逗号拆分为多个 dict-tag -->
      <el-table-column label="业务标签" align="center" prop="phoneTags">
        <template #default="{ row }">
          <div class="flex flex-wrap gap-1 justify-center">
            <dict-tag
              v-for="v in splitTags(row.phoneTags)"
              :key="v"
              :type="DICT_TYPE.PHONE_TAG"
              :value="v"
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column label="SecretAccountId" align="center" prop="secretId" />

      <el-table-column
        label="应答时间"
        align="center"
        prop="responseTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <!-- 应答状态列：使用 RESPONSE_STATE 字典渲染 -->
      <el-table-column label="应答状态" align="center" prop="responseState">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.RESPONSE_STATE" :value="row.responseState" />
        </template>
      </el-table-column>

      <el-table-column label="租户ID" align="center" prop="rechargeTenantId" />

      <el-table-column label="名单等级" align="center" prop="listLevel">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.LIST_LEVEL" :value="row.listLevel" />
        </template>
      </el-table-column>

      <!-- ✅ 营销工具列（仅展示，不作为搜索项） -->
      <el-table-column label="营销工具" align="center" prop="marketingTools">
        <template #default="{ row }">
          <div class="flex flex-wrap gap-1 justify-center">
            <dict-tag
              v-for="v in splitTags(row.marketingTools)"
              :key="v"
              :type="DICT_TYPE.MARKETING_TOOL"
              :value="v"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MarketingListLogForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MarketingListLogApi, MarketingListLog } from '@/api/vos/marketinglistlog'
import MarketingListLogForm from './MarketingListLogForm.vue'

defineOptions({ name: 'MarketingListLog' })

const { t } = useI18n()
const message = useMessage()

const loading = ref(false)
const exportLoading = ref(false)

/** 后端模型的本地扩展，避免 TS 报错 */
type LocalMarketingListLog = MarketingListLog & {
  marketingTools?: string
}

const list = ref<LocalMarketingListLog[]>([])
const total = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  phoneE164: undefined as string | undefined,
  score: undefined as number | undefined,

  // 与后端 LocalDateTime[] 对齐，value-format 已是字符串
  createTime: [] as string[],

  phoneMd5: undefined as string | undefined,

  // 多选数组，后端接收 List<String>，axios 默认序列化为重复 key
  phoneTags: [] as string[],

  secretId: undefined as number | string | undefined,

  responseTime: [] as string[],
  responseState: undefined as number | undefined, // 0/1/2

  rechargeTenantId: undefined as number | string | undefined,
  listLevel: undefined as string | undefined // 字符串枚举
})

const queryFormRef = ref()

/** 将逗号分隔的标签字符串拆成数组用于展示 */
const splitTags = (s?: string) => (s ? s.split(',').map(v => v.trim()).filter(Boolean) : [])

/** 发送前清洗空条件，避免空数组/不完整时间段参与查询 */
const normalizeQuery = (q: any) => {
  const cp: any = { ...q }
  if (!cp.createTime || cp.createTime.length !== 2) delete cp.createTime
  if (!cp.responseTime || cp.responseTime.length !== 2) delete cp.responseTime
  if (!cp.phoneTags || cp.phoneTags.length === 0) delete cp.phoneTags
  if (cp.phoneE164 === '' || cp.phoneE164 == null) delete cp.phoneE164
  if (cp.phoneMd5 === '' || cp.phoneMd5 == null) delete cp.phoneMd5
  if (cp.score === '' || cp.score == null) delete cp.score
  if (cp.secretId === '' || cp.secretId == null) delete cp.secretId
  if (cp.responseState === '' || cp.responseState == null) delete cp.responseState
  if (cp.rechargeTenantId === '' || cp.rechargeTenantId == null) delete cp.rechargeTenantId
  if (cp.listLevel === '' || cp.listLevel == null) delete cp.listLevel
  return cp
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const params = normalizeQuery(queryParams)
    const data = await MarketingListLogApi.getMarketingListLogPage(params)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

/** 搜索 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields?.()
  queryParams.phoneTags = [] // 手动清空多选
  queryParams.createTime = []
  queryParams.responseTime = []
  handleQuery()
}

/** 表单弹窗 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await MarketingListLogApi.deleteMarketingListLog(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {
    // ignore
  }
}

/** 批量删除 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: LocalMarketingListLog[]) => {
  checkedIds.value = records.map((item) => item.id as number)
}
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await MarketingListLogApi.deleteMarketingListLogList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {
    // ignore
  }
}

/** 导出 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params = normalizeQuery(queryParams)
    const data = await MarketingListLogApi.exportMarketingListLog(params)
    download.excel(data, '营销名单日志表（含应答状态）.xls')
  } catch {
    // ignore
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 */
onMounted(getList)
</script>

<style scoped>
/* 可选的微样式，提升可读性 */
:deep(.el-table .cell) {
  white-space: nowrap;
}
</style>
